<template>
  <div>

    <div style="position: relative;padding: 20px 30px;box-shadow: 0 0 10px rgba(0,0,0,.1);">
      <h4>监控管理</h4>
      <div
        style="position: absolute; top: 0; right: 30px;bottom: 0;display: flex;align-items: center;justify-content: center;">
        <h3 style="color: #FF9900;">{{ greeting }} {{ formattedTime }}</h3>
      </div>
    </div>
    <div class="boxCardText">
      <div class="Cardminbox">
        <span>
          监控延时/ms
        </span>
        <span class="card1txt">
          <span>{{ MoniTimeJk }}</span>小时
        </span>
      </div>



      <div class="Cardminbox2" @click="duanlianxichang">

        <span>
          短链异常数
        </span>
        <span class="card3txt">
          {{ this.abnormalNumber }}
        </span>
      </div>
      <!-- <div class="Cardminbox">
        <span>
          已监控时间
        </span>
        <span class="card2txt">
          {{ seconds }}秒
        </span>
      </div> -->


      <div>

      </div>
    </div>
    <el-card style="margin: 10px 0;">
      <el-input v-model="duaninput" placeholder="请输入短链地址" clearable style="width: 420px;margin: 0 10px;"></el-input>
      <el-button type="primary" @click="QueryDlList">查询</el-button>

      <br>
      <br>

      <el-button type="primary" @click="AddShortChain" size="medium">新增</el-button>
      <el-button type="primary" @click="AllAddchain = true" size="medium">批量新增</el-button>
      <el-button type="primary" @click="MonitorSettings" size="medium">监控设置</el-button>

      <el-button type="primary" @click="startTimer">开始监控</el-button>
      <el-button type="warning" @click="stopTimer">停止监控</el-button>
      <br>
      <br>

      <el-table :data="tableData.pageList" border style="width: 100%" ref="singleTable"
        @selection-change="handleSelectionChange" row-key="id">
        <el-table-column type="selection" align="center" width="55" :reserve-selection="true">
        </el-table-column>
        <el-table-column type="index" align="center" width="50">
        </el-table-column>
        <el-table-column prop="duanlian" align="center" label="监控短链" width="180">
        </el-table-column>
        <el-table-column prop="address" align="center" label="城市" width="180">
        </el-table-column>
        <el-table-column align="center" label="监控状态">
          <template slot-scope="scope">
            <span v-if="scope.row.checkStatus == 1" style="color: #000;">
              <b>未监控</b>
            </span>
            <span v-if="scope.row.checkStatus == 2" style="color: green;">
              <b>监控中</b>
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="域名对比">
          <template slot-scope="scope">
            <span v-if="scope.row.dns == 1">开启</span>
            <span v-if="scope.row.dns == 2">关闭</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="内容对比">
          <template slot-scope="scope">
            <span v-if="scope.row.con == 1">开启</span>
            <span v-if="scope.row.con == 2">关闭</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="最终网站">
          <template slot-scope="scope">
            <span style="width: 100px;overflow: auto;height: 100px;display: inline-block;">
              <a :href=scope.row.nomd5url target="_blank"> {{ scope.row.nomd5url }}</a>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="startData" align="center" label="开始时间">
        </el-table-column>
        <el-table-column prop="endData" align="center" label="结束时间">
        </el-table-column>
        <el-table-column prop="phone" align="center" label="手机号">
        </el-table-column>
        <el-table-column prop="beizhu" align="center" label="备注">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editChain(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="deleteChain(scope.row)">删除</el-button>

          </template>
        </el-table-column>
      </el-table>
      <el-pagination background @size-change="orderSizeChange" @current-change="orderCurrentChange"
        :page-sizes="[5, 10, 15, 20]" :page-size="10" :current-page="pageCode"
        t="total, sizes, prev, pager, next, jumper" :total="tableData.totalCount">
      </el-pagination>
    </el-card>

    <!--异常短链 弹窗 -->
    <el-dialog title="异常短链" :visible.sync="Abnormaldia">
      <el-table :data="abNumberList" border style="width: 100%">
        <el-table-column prop="msg" label="异常信息" width="180">
        </el-table-column>
        <el-table-column prop="beizhu" label="备注" width="180">
        </el-table-column>
        <el-table-column prop="address" label="地址">
        </el-table-column>
        <el-table-column prop="noMd5Url" label="最终地址">
        </el-table-column>
        <el-table-column prop="duanlian" label="短链">
        </el-table-column>
        <el-table-column prop="date" label="时间">
        </el-table-column>
      </el-table>

    </el-dialog>


    <!-- 新增弹窗 -->
    <el-dialog title="新增短链" :visible.sync="AddOneChain">
      <!-- <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"> -->
      <el-form :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="监控短链" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="短链备注" prop="remark">
          <el-input v-model="ruleForm.remark"></el-input>
        </el-form-item>

        <div style="display: flex;align-items: center;">
          <el-form-item label="域名对比" prop="delivery">
            <el-switch v-model="ruleForm.delivery" :active-value="1" :inactive-value="2"
              @change="changeSwitch"></el-switch>
          </el-form-item>
          <el-form-item label="内容对比" prop="Ncontent">
            <el-switch v-model="ruleForm.Ncontent" :active-value="1" :inactive-value="2"
              @change="changeSwitchTwo"></el-switch>
          </el-form-item>
        </div>
        <el-form-item label="城市" prop="city">
          <el-select v-model="ruleForm.city" multiple filterable placeholder="请选择" @change="changeCity">
            <el-option v-for="item in Cityptions" :key="item.value" :label="item.label" :value="item.label">
            </el-option>
          </el-select>

          <!-- <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
              @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
              <el-checkbox v-for="city in Cityptions" :label="city" :key="city">{{ city }}</el-checkbox>
            </el-checkbox-group> -->



        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="ruleForm.phone"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
          <el-button @click="resetForm('ruleForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 修改弹窗 -->
    <el-dialog title="修改短链" :visible.sync="editTwoChain">
      <el-form :model="editForm" ref="editForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="监控短链" prop="name">
          <el-input v-model="editForm.url" disabled></el-input>
        </el-form-item>
        <el-form-item label="短链备注" prop="remark">
          <el-input v-model="editForm.remark"></el-input>
        </el-form-item>

        <div style="display: flex;align-items: center;">
          <el-form-item label="域名对比" prop="dns">
            <el-switch v-model="editForm.dns" :active-value="1" :inactive-value="2" @change="changeSwitch2"></el-switch>
          </el-form-item>
          <el-form-item label="内容对比" prop="con">
            <el-switch v-model="editForm.con" :active-value="1" :inactive-value="2"
              @change="changeSwitchTwo2"></el-switch>
          </el-form-item>
        </div>
        <el-form-item label="城市" prop="city">
          <!-- <el-select v-model="ruleForm.city" placeholder="请选择活动区域">
            <el-option label="城市一" value="shanghai"></el-option>
            <el-option label="城市二" value="beijing"></el-option>
          </el-select> -->
          <!-- <el-input v-model="editForm.city"></el-input> -->

          <el-select v-model="editForm.city" multiple filterable placeholder="请选择" @change="changeCity">
            <el-option v-for="item in Cityptions" :key="item.value" :label="item.label" :value="item.label">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="editSubform()">确定</el-button>
          <el-button @click="editTwoChain = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 批量新增 -->
    <el-dialog title="批量新增" :visible.sync="AllAddchain" width="410px">
      <div>
        <el-upload class="upload-demo" drag ref="uploadKUser" :http-request="onUploadKUser" action=""
          :on-preview="handlePreviewKUser" :on-remove="handleRemoveKUser" :file-list="fileListKUser"
          :on-change="handleFileChange" :on-success="uploadSuccess" :multiple="true" :auto-upload="false" accept=""
          :limit="50" :on-exceed="OnExceedKUser">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AllAddchain = false">取 消</el-button>
        <el-button type="primary" @click="SureAllAdd()">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog title="监控设置" :visible.sync="centerDialogVisible" width="30%" center>
      <div>
        <span>监控延时：</span>
        <el-select v-model="MoniTimeJk2" placeholder="请选择监控时长">
          <el-option v-for="item in MonitoringTime" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <br>
      <!-- <div>
      <span>监控时间：</span>
      <el-date-picker v-model="DateandTime" type="datetimerange" :picker-options="pickerOptions" range-separator="至"
        start-placeholder="开始日期" end-placeholder="结束日期" align="right" value-format="yyyy-MM-dd HH:mm:ss" @change="ChangeTimeData">
      </el-date-picker>
     </div> -->


      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="SetJianKTime">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  QueryByPage, AddshortChain, ChainMonitor, ChangeChain, DelChain,
  AddAllChain, BatchMonito, AllCities, BatchEndMon,
  setTime
} from '@/api/table'
export default {
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      DateandTime: '',
      isIndeterminate: true,
      checkAll: false,
      checkedCities: [],
      seconds: 0, // 用来记录经过的秒数
      timerRunning: false, // 定时器是否正在运行
      timer: null, // 定时器的引用
      pageCode: 1,
      pageSize: 10,
      totalCount: 1,
      centerDialogVisible: false,
      duaninput: '',
      checkAll: false,
      isIndeterminate: true,
      AddOneChain: false,   //新增短链
      activeName: 'first',
      currentTime: new Date(),
      Abnormaldia: false,
      editTwoChain: false,   //修改短链
      AllAddchain: false,  //批量新增
      tableData: [],
      abNumberList: [],
      fileListKUser: [],
      BatchChains: [],
      ruleForm: {
        name: '',
        city: '',
        remark: "",
        delivery: 2,
        Ncontent: 2,
        phone: '',
      },
      editForm: {
        phone: '',
        city: '',
        con: "",
        dns: "",
        remark: '',
        url: '',
        id: ''
      },
      abnormalNumber: 0,
      Cityptions: [],
      MonitoringTime: [
        {
          value: 1,
          label: '1小时'
        },
        {
          value: 4,
          label: '4小时'
        },
        {
          value: 8,
          label: '8小时'
        },
        {
          value: 12,
          label: '12小时'
        },
        {
          value: 24,
          label: '24小时'
        }
      ],
      MoniTimeJk: 0,
      MoniTimeJk2: 0,

      rules: {
        name: [
          { required: true, message: '请输入监控短链', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入短链备注', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { min: 11, max: 11, message: '长度在 11位数字', trigger: 'blur' }
        ],


      }

    };
  },
  computed: {
    formattedTime() {
      const options = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
      };
      return this.currentTime.toLocaleString('zh-CN', options).replace(/\//g, '-');
    },
    greeting() {
      const hour = this.currentTime.getHours();
      if (hour < 12) {
        return '早上好！';
      } else if (hour < 18) {
        return '下午好！';
      } else {
        return '晚上好！';
      }
    },
  },
  mounted() {
    this.updateTime();
    setInterval(this.updateTime, 1000); // 每秒更新一次时间
  },
  created() {
    this.QueryDlList()
    // // 页面刷新后检查 localStorage 是否有定时器状态
    if (localStorage.getItem('timerRunning') === 'true') {
      this.timerRunning = true;
      // this.seconds = parseInt(localStorage.getItem('seconds'), 10);
      this.startInterval();
    }
    this.QueryAllCities()
    let setdliantime = localStorage.getItem('MoniTimeJk')
    if (setdliantime) {
      this.MoniTimeJk = setdliantime
    } else {
      localStorage.setItem('MoniTimeJk', 4);

    }
  this.startOrStop()
  },
  beforeDestroy() {
    // 在组件销毁时，清理定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    handleCheckAllChange(val) {
      const Cityptions2 = this.Cityptions;
      this.checkedCities = val ? Cityptions2 : [];
      this.isIndeterminate = false;
      // console.log(this.checkedCities, "全部选中的")

    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.Cityptions.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.Cityptions.length;
      // console.log(this.checkedCities, "单选选中的")

    },
    // 设置监控时间
    SetJianKTime() {
      setTime({ num: this.MoniTimeJk2 }).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.msg)
          this.MoniTimeJk = this.MoniTimeJk2
          this.centerDialogVisible = false
          localStorage.setItem('MoniTimeJk', this.MoniTimeJk);

        } else {
          this.$message.error(res.msg)

        }
      })

    },
    ChangeTimeData(e) {
      console.log(e)
    },

    // 监控设置
    MonitorSettings() {
      this.centerDialogVisible = true
    },
    async QueryAllCities() {
      let res = await AllCities()
      const result = res.data
      // const names = result.map(item => item.label);
      this.Cityptions = result
    },

 duanlianxichang(){
  this.Abnormaldia = true
  this.startOrStop()
 },

    async onUploadKUser(file) {

      const formData = new FormData()
      formData.append("file", file.file);
      let UpFiles = await AddAllChain(formData);
      // console.log(UpFiles)
      if (UpFiles.code === 200) {
        this.$message({
          message: UpFiles.data,
          type: 'success',
          duration: 1000
        });
        this.AllAddchain = false
        this.fileListKUser = [];
        this.QueryDlList()
      } else {
        this.$message({
          message: UpFiles.msg,
          type: 'error',
          duration: 1000
        });
      }

    },

    SureAllAdd() {
      this.$refs.uploadKUser.submit();
      this.AllAddchain = false

    },
    handleSelectionChange(val) {
      const newValueArray = val.map(item => item.id);
      this.BatchChains = newValueArray
    },
    // 城市选择
    changeCity() {
      console.log(this.ruleForm.city, "城市选择")
    },
    // 删除
    deleteChain(row) {
      let data = {
        id: row.id,
        duanlian: row.duanlian
      }
      this.$confirm('此操作将永久删除该短链, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await DelChain(data)
        if (res.code === 200) {
          this.$message.success(res.data)
          this.QueryDlList()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 修改
    editChain(e) {
      // console.log(e)
      this.editTwoChain = true
      const result = e.address.split(", ")
      this.editForm.url = e.duanlian
      this.editForm.phone = e.phone
      this.editForm.remark = e.beizhu
      this.editForm.con = e.con
      this.editForm.dns = e.dns
      this.editForm.city = result
      this.editForm.id = e.id
    },
    async editSubform() {
      const result = this.editForm.city.join(", ")
      let data = {
        address: result,
        beizhu: this.editForm.remark,
        con: this.editForm.con,
        dns: this.editForm.dns,
        duanlian: this.editForm.url,
        phone: this.editForm.phone,
        id: this.editForm.id
      }
      let res = await ChangeChain(data)
      if (res.code === 200) {
        this.$message.success(res.data)
        this.editTwoChain = false
        this.QueryDlList()

      } else {
        this.$message.error(res.msg)
      }
    },
    // 取消选择
    setCurrent() {
      this.$refs.singleTable.clearSelection();
    },

    // 开始监控
    async startOrStop() {
      // let data = {
      //   pageCode:1,
      //   pageSize:10
      // }
      let res = await ChainMonitor()
      this.abnormalNumber = res.data.length
      this.abNumberList = res.data
      if (res.data.length > 0) {
        this.$notify({
          title: '警告',
          duration: 1000,
          type: 'warning',
          dangerouslyUseHTMLString: true,
          message: `短链异常数量:${res.data.length}`
        });
      } else {
        // this.$notify({
        //   title: '成功',
        //   message: '无异常',
        //   type: 'success'
        // });
      }
    },

    async startTimer() {
      if (this.BatchChains.length > 0) {
        let res = await BatchMonito({ list: this.BatchChains })
        // console.log(res, "批量监控")
        if (res.code === 200) {
          this.$message.success(res.data)
          this.timerRunning = true;
          this.startOrStop()
          this.startInterval();
          // 保存定时器状态到 localStorage
          localStorage.setItem('timerRunning', 'true');
          this.BatchChains = []
          this.QueryDlList()
          this.setCurrent()
        } else {
          this.$message.error(res.msg)
        }
      } else {
        this.$message.warning("请选择监控的短链")
      }
    },
    async stopTimer() {
      if (this.BatchChains.length > 0) {
        let res = await BatchEndMon({ list: this.BatchChains })
        // console.log(res, "批量结束监控")
        if (res.code === 200) {
          this.$message.success(res.data)
          this.timerRunning = false;
          clearInterval(this.timer);
          // 停止定时器后，清空 localStorage 中的状态
          localStorage.setItem('timerRunning', 'false');
          this.QueryDlList()
          this.setCurrent()
        } else {
          this.$message.error(res.msg)
        }
      } else {
        this.$message.warning("请选择停止监控的短链")

      }
    },
    startInterval() {
      // 每秒更新一次秒数
      if (this.MoniTimeJk == 1) {
        this.timer = setInterval(() => {
          this.startOrStop()
        }, 1 * 3600 * 3000);
      } else if (this.MoniTimeJk == 4) {
        this.timer = setInterval(() => {
          this.startOrStop()
        }, 4 * 3600 * 1000);
      } else if (this.MoniTimeJk == 8) {
        this.timer = setInterval(() => {
          this.startOrStop()
        }, 8 * 3600 * 1000);
      } else if (this.MoniTimeJk == 12) {
        this.timer = setInterval(() => {
          this.startOrStop()
        }, 12 * 3600 * 1000);
      } else if (this.MoniTimeJk == 24) {
        this.timer = setInterval(() => {
          this.startOrStop()
        }, 24 * 3600 * 1000);
      }
    },
    changeSwitch(e) {
      this.ruleForm.delivery = e
      // console.log(this.ruleForm.delivery)
    },
    changeSwitchTwo(e) {
      this.ruleForm.Ncontent = e
    },
    changeSwitch2(e) {
      this.editForm.dns = e
    },
    changeSwitchTwo2(e) {
      this.editForm.con = e
    },
    // 查询断链
    async QueryDlList() {
      let data = {
        pageCode: this.pageCode,
        pageSize: this.pageSize,
        duanlian: this.duaninput
      }
      let res = await QueryByPage(data)
      if (res.code === 200) {
        // this.$message.success(res.msg)
        this.tableData = res.data
      } else {
        this.$message.error(res.msg)
      }
    },
    AddShortChain() {
      this.AddOneChain = true
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        // if (valid) {
        //   alert('submit!');
        // } else {
        //   console.log('error submit!!');
        //   return false;
        // }
        const result = this.ruleForm.city.join(", ")
        let data = {
          address: result,
          beizhu: this.ruleForm.remark,
          con: this.ruleForm.Ncontent,
          dns: this.ruleForm.delivery,
          duanlian: this.ruleForm.name,
          phone: this.ruleForm.phone,
        }
        AddshortChain(data).then(res => {
          if (res.code === 200) {
            this.$message.success(res.msg)
            this.AddOneChain = false
            this.QueryDlList()
          } else {
            this.$message.error(res.msg)
          }
        })
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.AddOneChain = false
    },
    updateTime() {
      this.currentTime = new Date();
    },

    async orderSizeChange(val) {
      this.pageSize = val;
      this.QueryDlList();
    },
    async orderCurrentChange(val) {
      this.pageCode = val;
      this.QueryDlList();
    },
    handlePreviewKUser(file) {
      // console.log(file, "1");
    },
    // 	文件列表移除文件时的钩子
    handleRemoveKUser(file, fileList) {
      // console.log(file, fileList, "文件列表移除文件时的钩子");
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handleFileChange(file, fileList) {
      // console.log(file, fileList, "this.fileListKUser")
    },
    // 上传成功
    uploadSuccess(response, file, fileList) {
      // console.log('上传成功')
    },
    OnExceedKUser() {
      this.$message({
        message: "文件上传超出限制",
        type: 'error'
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.boxCardText {
  padding: 20px 30px;
  position: relative;
  display: flex;
  align-items: center;
  box-shadow: 0 0 20px #fff;
  margin: 5px 0;
}

.Cardminbox {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-direction: column;
  margin: 0 20px;
}

.Cardminbox2 {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-direction: column;
  margin: 0 20px;
  cursor: pointer;
}

.card1txt {
  margin-top: 20px;
  font-weight: 600;
}

.card2txt {
  margin-top: 20px;
  font-weight: 600;
  color: #FF9900;
}

.card3txt {
  margin-top: 20px;
  font-weight: 600;
  color: #FF0000;
}
</style>
